<template>
  <div class="status-content">
    <div class="select-header" :style="{ maxHeight: 'calc(100% - 400px)' }">
      <!-- <span>
                存储数据源：
                <a-select v-model="dataSource" placeholder="请选择" style="width: 120px;">
                    <a-select-option value="gp">
                        gp
                    </a-select-option>
                </a-select>
            </span> -->
      <span>
        数据类型：
        <a-select
          v-model="dataType"
          :allow-clear="true"
          placeholder="请选择"
          style="width: 120px;"
        >
          <a-select-option value="table">table</a-select-option>
          <a-select-option value="csv">csv</a-select-option>
          <a-select-option value="file">file</a-select-option>
          <a-select-option value="http">http</a-select-option>
          <a-select-option value="excel">excel</a-select-option>
          <a-select-option value="pipeline">pipeline</a-select-option>
        </a-select>
      </span>
      <span>
        数据表名称：
        <a-input
          v-model="name"
          :allow-clear="true"
          style="width: 180px;"
          placeholder="请输入文字检索"
        />
        <a-button type="primary" style="margin-left: 20px;" @click="searchData">
          搜索
        </a-button>
      </span>
    </div>
    <div class="table-content" :style="{ maxHeight: 'calc(100% - 400px)' }">
      <a-table
        :columns="columns"
        :data-source="datasetsList"
        :scroll="{ y: height }"
        :pagination="{ showSizeChanger: true }"
      >
        <span slot="action" slot-scope="text, record">
          <span class="action-item" @click="gotoDataView(record)">查看</span>
          <a-divider type="vertical" />
          <span v-if="record.dataType === 'table'">
            <span class="action-item" @click="showEditModal(record)">编辑</span>
            <a-divider type="vertical" />
          </span>
          <a-tooltip>
            <template slot="title"> 数据历史 </template>
            <span class="action-item" @click="showHistory(record)">历史</span>
          </a-tooltip>
          <a-divider type="vertical" />
          <span class="action-item" @click="setDeleteVisible(record)"
            >删除</span
          >
        </span>
      </a-table>
    </div>
    <drawer
      placement="right"
      width="444"
      :mask="false"
      :closable="false"
      :destroy-on-close="false"
      :visible="isInStatus && isHistoryShow"
      :after-visible-change="afterVisibleChange"
    >
      <div slot="title">
        <a-icon-font type="iconicon-beifen-right" @click="onClose" />
        <span class="drawer-title">数据历史</span>
      </div>

      <div>
        <span class="table-name">{{ selectedRecord.name }}</span>
        <span class="date-select">
          <a-select
            v-model="dateRange"
            style="width: 120px;"
            @change="handleDateChange"
          >
            <a-select-option value="null">全部记录</a-select-option>
            <a-select-option value="7">近7日</a-select-option>
            <a-select-option value="14">近14日</a-select-option>
            <a-select-option value="30">近30日</a-select-option>
          </a-select>
        </span>
      </div>

      <div class="chart-content">
        <!-- <div v-if="chartData.length===0">不存在数据删改操作</div>
                <div v-else> -->
        <Chart :chart-type="'lineChart'" :config="commonConfig" />
        <!-- </div> -->
      </div>
    </drawer>
    <!-- <DataEditModal :selectedDatabaseType="selectedRecord.type"></DataEditModal> -->
    <!-- <dataset-edit-panel :selected-dataset="selectedRecord.id"/> -->
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { Drawer, Modal } from 'ant-design-vue'
import DataStore from '@/store/modules/data'
import moment from 'moment'
import Chart from '@/components/chart/chart.vue'
import DeleteDatasetContent from '@/components/data/DeleteDatasetContent.vue'
import { queryDatasetUsedInfo } from '@/api/data'

@Component({
  components: {
    Drawer,
    Chart,
    DeleteDatasetContent,
    // DataEditModal
  },
})
export default class DataStatusPage extends Vue {
  private isHistoryShow: boolean = false // 是否显示数据历史面板
  private name: string = ''
  private dataSource: string = ''
  private dataType: string = ''
  private dateRange = 'null'
  private selectedRecord: any = {}
  private deleteVisible: boolean = false
  private height: number = document.body.clientHeight - 400
  private transferUserId: any = -1

  public handleResize() {
    this.height = document.body.clientHeight - 400
  }

  public async created(): Promise<void> {
    this.height = document.body.clientHeight - 400
    window.addEventListener('resize', this.handleResize)
    await DataStore.queryDatasetsList(this.postData)
  }

  private get isInStatus() {
    if (this.$route.path !== '/management/data/status') {
      this.isHistoryShow = false
    }
    return this.$route.path === '/management/data/status'
  }

  private columns = [
    {
      title: '数据表名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '数据源类型',
      dataIndex: 'dataType',
      key: 'dataType',
    },
    // {
    //     title: '存储数据源',
    //     key: 'dataSource',
    //     dataIndex: 'dataSource',
    //     scopedSlots: { customRender: 'dataSource' },
    // },
    {
      title: '创建时间',
      key: 'create',
      dataIndex: 'create',
      scopedSlots: { customRender: 'create' },
      sorter: (a: any, b: any) => (a.create > b.create ? 1 : -1),
    },
    {
      title: '更新时间',
      key: 'modify',
      dataIndex: 'modify',
      scopedSlots: { customRender: 'modify' },
      sorter: (a: any, b: any) => (a.modify > b.modify ? 1 : -1),
    },
    {
      title: '行数',
      key: 'rowNum',
      dataIndex: 'rowNum',
      scopedSlots: { customRender: 'rowNum' },
      sorter: (a: any, b: any) => (a.rowNum > b.rowNum ? 1 : -1),
    },
    {
      title: '操作',
      key: 'action',
      scopedSlots: { customRender: 'action' },
    },
  ]

  private chartData: any[] = []

  public get commonConfig() {
    return {
      value: this.chartData,
      labelKey: 'date',
      valueKey: 'rows',
      xAxisFontSize: 12,
      size: [400, 250],
      xAxisTitleIsShow: false,
      yAxisTitleIsShow: false,
      xAxisTitle: '时间',
      yAxisTitle: '行数',
      xAxisTitleFontSize: 12,
      yAxisTitleFontSize: 12,
      titleIsShow: false,
      pointRadius: 2,
    }
  }

  /* 获取数据集列表 */
  public get datasetsList() {
    const list: any[] = []
    if (DataStore.datasetsList.length !== 0) {
      DataStore.datasetsList.forEach((item: any, index: any) => {
        list.push({
          key: index + 1,
          id: item.id,
          name: item.name,
          dataSource: item.dataSource,
          dataType: item.dataType,
          create: moment(item.gmtCreate).format('YYYY-MM-DD HH:mm:ss'),
          modify: moment(item.gmtModify).format('YYYY-MM-DD HH:mm:ss'),
          rowNum: item.rowNum,
        })
      })
    }

    return list
  }

  /* 搜索条件传参 */
  public get postData() {
    return {
      dataSource: this.dataSource === '' ? null : this.dataSource,
      dataType: this.dataType === '' ? null : this.dataType,
      name: this.name === '' ? null : this.name,
    }
  }

  /* 搜索数据 */
  public async searchData() {
    await DataStore.queryDatasetsList(this.postData)
  }

  /* 编辑数据集 */
  public async showEditModal(record: any) {
    console.log(record)
    DataStore.setSelectedDatasetId(record.id)
    await DataStore.queryDataset(record.id)
    DataStore.setDatasetEditModalVisible(true)
    DataStore.setIsClearForm(true)
  }

  public afterVisibleChange(value: boolean) {
    console.log('visible', value)
  }

  /* 显示数据历史面板 */
  public showHistory(record: any) {
    console.log(record)
    this.dateRange = 'null'
    this.selectedRecord = record
    this.isHistoryShow = true

    this.updateActionHistory()
  }

  private isChanged: boolean = false

  /* 更新数据历史，处理折线图数据 */
  public async updateActionHistory() {
    const passData = {
      id: this.selectedRecord.id,
      daydiff: this.dateRange,
    }
    const response = await DataStore.queryActionByDataId(passData)
    this.chartData = []
    if (response !== null) {
      this.isChanged = true
      response.forEach((item: any) => {
        this.chartData.push({
          date: moment(item.gmtCreate).format('MM-DD HH:mm'),
          rows: item.rowFinal,
        })
      })
    } else {
      this.isChanged = false
      this.chartData.push({
        date: moment(this.selectedRecord.create).format('MM-DD HH:mm'),
        rows: this.selectedRecord.rowNum,
      })
    }
    console.log(this.chartData)
  }

  /* 关闭数据历史面板 */
  public onClose() {
    this.isHistoryShow = false
  }

  /* 改变数据历史时间范围，更新数据历史 */
  public async handleDateChange() {
    this.updateActionHistory()
  }

  /* 删除数据集面板 */
  public async setDeleteVisible(record: any) {
    const response = await queryDatasetUsedInfo({
      data: { datasetId: record.id },
    })
    const dataset = response.data.result
    if (dataset.length !== 0) {
      this.transferUserId = dataset[0].userId
    }
    this.selectedRecord = record
    this.deleteVisible = true
    Modal.confirm({
      title: '确认要删除该数据表吗？',
      content: () =>
        this.$createElement('delete-dataset-content', {
          props: {
            dataset,
            setTransferUserId: (value: any) => {
              this.transferUserId = value
            },
          },
        }),
      okText: '确定',
      cancelText: '取消',
      onOk: this.deleteDataset,
      onCancel: this.cancelDelete,
    })
  }

  /** 取消 */
  public cancelDelete() {
    this.deleteVisible = false
  }

  /** 删除数据表 */
  public async deleteDataset() {
    const response = await DataStore.deleteDataset({
      id: this.selectedRecord.id,
      transferUserId: this.transferUserId,
    })
    await DataStore.queryDatasetsList(this.postData)
    this.deleteVisible = false
    if (response.data.code === 100) {
      DataStore.setSelectedDatasetId(-1)
    }
  }

  /* 查看数据表，跳转到数据内容页面 */
  public gotoDataView(record: any) {
    this.$router.push('/management/data')
    this.$nextTick(() => {
      DataStore.setDataTabIndex('1')
      DataStore.setSelectedDatasetId(record.id)
      DataStore.setDatasetId(record.name)
      DataStore.setCategoryId('')
    })
  }
}
</script>

<style lang="less" scoped>
.status-content {
  max-height: calc(100vh - 240px);
  min-height: calc(100vh - 240px);
  padding-right: 24px;
}

.select-header {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  margin-top: 12px;

  span {
    margin-right: 20px;
  }
}

.table-content {
  margin-top: 24px;
  max-height: calc(100vh - 500px);
  min-height: calc(100vh - 500px);
}

/deep/ .action-item {
  color: #373b52;
  cursor: pointer;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 1px;
  line-height: 20px;

  &:hover {
    color: #6973ff;
  }
}

/deep/ .action-item-disabled {
  color: #adaeb8;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 1px;
  line-height: 20px;
}

.history-panel {
  background: #fff;
  height: calc(100vh - 140px);
  overflow: visible;
  position: absolute;
  right: 0;
  top: 0;
  width: 444px;
  z-index: 2220;

  .history-header {
    border-bottom: 1px solid #ededed;
    color: #373b52;
    font-size: 14px;
    font-weight: 600;
    height: 52px;
    letter-spacing: 1px;
    line-height: 52px;
    padding-left: 20px;
    padding-right: 20px;
    width: 100%;
  }

  .history-btns {
    height: 50px;
    line-height: 50px;

    .btn-item {
      padding-left: 22px;
      padding-right: 16px;
    }
  }
}

.drawer-title {
  margin-left: 14px;
}

.table-name {
  color: #373b52;
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 1px;
  line-height: 20px;
}

.date-select {
  float: right;
}

.chart-content {
  height: 500px;
  margin-top: 25px;
}

/deep/ .ant-table-body,
/deep/ .ant-table-body-inner {
  overflow-y: auto !important;

  &::-webkit-scrollbar {
    height: 6px;
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.5);
    border-radius: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 5px;
  }
}

/deep/ .ant-drawer-content-wrapper {
  top: 124px;
}
</style>
